/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "d3d_local.h"

/*-----------------------------------------------------------------------------
	D3D FX manager :
-----------------------------------------------------------------------------*/
				 
//
//	ED3DFXManager::ED3DFXManager
//
ED3DFXManager::ED3DFXManager( ED3DDriver *driver )
{
	this->driver	=	driver;
}


//
//	ED3DFXManager::~ED3DFXManager
//
ED3DFXManager::~ED3DFXManager( void )
{
	effects.clear();
}


//
//	ED3DFXManager::CompileEffect
//
IPxEffect ED3DFXManager::CompileEffect( const EString path, uint num_macros/* =0 */, EFXMacro *macros/* =NULL */ )
{
	ID3DXEffect	*d3dfx = CompileEffect( path.CStr(), num_macros, macros );

	if (!d3dfx) {
		return NULL;
	}
	
	IPxEffect	effect = new ED3DEffect(this, d3dfx);
	
	effects.push_back( effect );
	
	return effect;
}


//
//	ED3DFXManager::ClearEffects
//
void ED3DFXManager::ClearEffects( void )
{
	effects.clear();
}


/*-----------------------------------------------------------------------------
	Compiling stuff :
-----------------------------------------------------------------------------*/
				 
class	ED3DInclude : public ID3DXInclude {
	public:
						ED3DInclude		( void );
						~ED3DInclude	( void );
		STDMETHOD(Open) 	( D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes );
		STDMETHOD(Close)	( LPCVOID pData );
	protected:
	};	
		

ED3DInclude::ED3DInclude( void )	{	}
ED3DInclude::~ED3DInclude( void )	{	}

//
//	ED3DInclude::Open
//
HRESULT ED3DInclude::Open( D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes )
{
	try {

		IHrFile	 f;

		if ( fs()->isFileExist(pFileName) ) {
			f	=	fs()->openFile(pFileName, FS_OPEN_READ);
		} else {
			f	=	fs()->openFile(va("shaders/%s", pFileName), FS_OPEN_READ);
		}
	
		uint	sz	=	f->size();
		LPCVOID		data	=	malloc( sz );
		f->read(const_cast<void*>(data), sz);
		
		*pBytes	=	sz;
		*ppData	=	data;
		
		return S_OK;
		
	} catch (filesystem_exception &e) {
		return S_FALSE;
	}
}


//
//	ED3DInclude::Close
//
HRESULT ED3DInclude::Close( LPCVOID pData )
{
	free(const_cast<void*>(pData));
	return S_OK;
}


//
//	LogFXCompileMessage
//
static void LogFXCompileMessage( bool is_error, string &str )
{
	uint n0 = 0;
	uint n1 = str.find('\n', n0);
	
	do {		
		string s = str.substr(n0, n1-n0);
		n0 = n1+1;
		n1 = str.find('\n', n0);
		
		if (is_error) {
			LOG_ERROR("%s", s.c_str());
		} else {
			LOG_WARNING("%s", s.c_str());
		}
		
	} while (n1!=string::npos);
}


//
//	PrefixNewLine
//	- adds backslashes before '\n'
//
static EString	PrefixNewLine( const EString definition )
{
	vector<char>	buffer;
	buffer.reserve( definition.Length() + 20 );	// add some bytes to avoid extra allocations
	
	for (uint i=0; i<definition.Length(); i++) {
		char ch = definition.CStr()[ i ];
		
		if (ch=='\n') { 
			buffer.push_back('\\');
		}
		
		buffer.push_back( ch );
	}
	
	buffer.push_back('\0');

	if (buffer.empty()) {
		return EString("");
	}	
	
	return EString( &buffer[0] );
}


//
//	ED3DRenderSystem::CompileEffect
//
ID3DXEffect *ED3DFXManager::CompileEffect( const char *path, uint num_macros/* =0 */, EFXMacro *macros/* =NULL */ )
{
	ID3DXEffect	*effect = NULL;
	ID3DXBuffer	*errors = NULL;
	ED3DInclude	include;
	uint		flags	= 0;//D3DXFX_NOT_CLONEABLE;

	LOGF("compiling : %s", path);

	//	resolve path :
	EString	path_alt = fs()->resolvePath( path );
	
	//	make macros :
	D3DXMACRO null_macro	= {NULL, NULL};
	D3DXMACRO *macro_ptr	= NULL;
	vector<D3DXMACRO>	d3dmacros;
	vector<EString>		definitions;
	definitions.resize( num_macros, "" );
	d3dmacros.resize( num_macros+2, null_macro );

	for (uint i=0; i<num_macros; i++) {
		definitions[i] = PrefixNewLine( macros[i].definition );
	}

	for (uint i=0; i<num_macros; i++) {
		d3dmacros[i].Name		=	macros[i].name.CStr();
		d3dmacros[i].Definition	=	definitions[i].CStr();
	}	
	
	
	macro_ptr = d3dmacros.empty() ? NULL : &d3dmacros[0];
	
	//	compile :	
	HRESULT hr = D3DXCreateEffectFromFile( driver->GetDevice(), path_alt.CStr(), macro_ptr, &include, flags, NULL, &effect, &errors );

	//	deal with errors :	
	if (FAILED(hr)) {
	
		effect = NULL;
		
		if (errors) {
			string msg = (char*)errors->GetBufferPointer();
			LogFXCompileMessage(true, msg);
			
			LOG_ERROR("definitions :");
			for (uint i=0; i<num_macros; i++) {
				LOG_ERROR("   %-20s = %s", d3dmacros[i].Name, d3dmacros[i].Definition );
			}
		} else {
			ASSERT(0);
			LOG_ERROR("file not found: %s", path);
		}
		
	} else if (errors) {
		string msg = (char*)errors->GetBufferPointer();
		LogFXCompileMessage(true, msg);
	}
	
	return effect;
}

